<template>
  <div class="pici-container">
    <!-- 面包屑 -->
    <div style="width: auto;height: 60px;font-size: larger;">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/Main' }">仪表台</el-breadcrumb-item>
        <el-breadcrumb-item>批次管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 查询、表格和分页容器 -->
    <div class="data-container">
      <!-- 查询 -->
      <div class="search-section">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          
          <el-form-item label="货品名称:">
            <el-input v-model="formInline.Goodsname" placeholder="货品名称" clearable />
          </el-form-item>
          <el-form-item label="批次编码:">
            <el-input v-model="formInline.PiciCoding" placeholder="批次编码" clearable />
          </el-form-item>
          <el-form-item label="仓库名称">
            <el-select v-model="formInline.Warename" placeholder="请选择所属仓库" style="width: 240px">
              <el-option v-for="item in wareHouseOptions" :key="item.warehouseNo" :label="item.warename" :value="item.warehouseNo" />
            </el-select>
          </el-form-item>
          <el-form-item label="货品类型">
            <el-select v-model="formInline.Goodstypeid" placeholder="请选择货品类型" style="width: 240px">
              <el-option v-for="item in goodsTypes" :key="item.goodstypecoding" :label="item.wGoodstypename" :value="item.goodstypecoding" />
            </el-select>
          </el-form-item>
          <el-form-item label="单位">
            <el-select v-model="formInline.GoodsUnitId" placeholder="请选择单位" style="width: 240px">
              <el-option v-for="item in Units" :key="item.unitscoding" :label="item.unitName" :value="item.unitscoding" />
            </el-select>
          </el-form-item>
                    <el-form-item label="生产时间:">
            <el-date-picker
               v-model="formInline.ProductionTime"
              type="date"
              placeholder="请选择生产时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              clearable
              />
          </el-form-item>
          <el-form-item label="到期时间:">
            <el-date-picker
               v-model="formInline.EndTime"
               type="date"
               placeholder="请选择到期时间"
               format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
      />
           
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit" >搜索</el-button>
            <el-button type="primary" @click="Reset">重置</el-button>
            <el-button type="success" @click="exportData" :disabled="tableData.length === 0">导出</el-button>
            <el-button type="info" @click="refreshData" :loading="loading">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 表格 -->
      <div class="table-section">
        <el-table 
          :data="tableData" 
          style="width: 100%" 
          v-loading="loading" 
          stripe
          :empty-text="loading ? '加载中...' : '暂无数据'"
        >
          <el-table-column fixed type="index" label="行号" width="80" />
          <el-table-column fixed prop="goodscoding" label="货品编码" width="180"/>
          <el-table-column fixed prop="goodsname" label="货品名称" width="150" />
          <el-table-column prop="goodstyoeName" label="货品类型" width="120" />
          <el-table-column prop="goodsspecifications" label="规格" width="100" />
          <el-table-column prop="goodsUnitName" label="单位" width="80" />
          <el-table-column prop="wsorting" label="当前库存" width="80" />
          <el-table-column prop="piciCoding" label="批次编码" width="150" />
            
          <el-table-column prop="productionTime" label="生产日期" width="120">
            <template v-slot="scope">
              {{ formatDate(scope.row.productionTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="endTimes" label="到期日期" width="120">
            <template v-slot="scope">
              {{ formatDate(scope.row.endTimes) }}
            </template>
          </el-table-column>
          <el-table-column prop="warename" label="仓库名称" width="120" />
          <el-table-column prop="locationName" label="库位名称" width="120" />
         
        </el-table>
      </div>
        <!-- 分页 -->
    <table>
            <tr>
                <th>
                    <el-pagination v-model:current-page="formInline.PageIndex" v-model:page-size="formInline.PageSize"
                        :page-sizes="[10, 20, 30, 40, 50]" layout="slot, sizes" :total="formInline.count">
                        当前第{{ formInline.PageIndex }}页/共{{ formInline.pcount}}页/共{{
                            formInline.count 
                        }}条
                    </el-pagination>
                </th>
                <th>
                    <el-pagination v-model:current-page="formInline.PageIndex" v-model:page-size="formInline.PageSize"
                        :page-sizes="[10, 20, 30, 40, 50]" layout="slot, prev, pager, next" :total="formInline.count">
                        <el-button :disabled="formInline.PageIndex == 1" @click="formInline.PageIndex = 1"
                            type="primary">首页</el-button>
                    </el-pagination>
                </th>
                <th>
                    <el-pagination v-model:current-page="formInline.PageIndex" v-model:page-size="formInline.PageSize"
                        :page-sizes="[10, 20, 30, 40, 50]" layout="slot,jumper" :total="formInline.count">
                        <el-button :disabled="formInline.PageIndex == formInline.pcount" @click="formInline.PageIndex = formInline.PageSize"
                            type="primary">尾页</el-button>
                    </el-pagination>
                </th>
            </tr>
        </table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import service from '@/utils/request'

// 组件挂载时初始化数据
onMounted(() => {
  GetSelectWareHouse()
  GetSelectTypes()
  GetSelectUnits()
  getPiciData()
})


// 查询表单
const formInline = reactive({
  PageIndex:1,
  PageSize:10,
  Goodsname: '',
  Goodstypeid: '',
  GoodsUnitId: '',
  PiciCoding: '',
  Warename: '',
  ProductionTime: '',
  EndTime: '',
  count:0,
  pcount:0
})
const tableData = ref([])
const loading = ref(false)
// 获取批次数据
const getPiciData = async () => {
  loading.value = true
  try {
    // 构建请求参数，使用正确的参数名称
    const params = {
      PageIndex: formInline.PageIndex,
      PageSize: formInline.PageSize,
      Goodsname: formInline.Goodsname,
      Goodstypeid: formInline.Goodstypeid,
      GoodsUnitId: formInline.GoodsUnitId,
      PiciCoding: formInline.PiciCoding,
      Warename: formInline.Warename,
      ProductionTime: formInline.ProductionTime ? formInline.ProductionTime.substring(0, 10) : '',
      EndTime: formInline.EndTime ? formInline.EndTime.substring(0, 10) : ''
    }
    // 过滤掉空值参数
    const filteredParams = Object.fromEntries(
      Object.entries(params).filter(([key, value]) => value !== '' && value !== null && value !== undefined)
    )
    
    console.log('发送的参数:', filteredParams)
    
    const response = await service.get('/api/app/standing__Book/pici', { params: filteredParams })
    
    if (response.data.code === 200) {
      tableData.value = response.data.pageDatas
      formInline.count = response.data.totalData
      formInline.pcount = response.data.totalPage
    } else {
      ElMessage.error(response.data.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取批次数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const onSubmit = () => {
  formInline.PageIndex = 1
  getPiciData()
}

// 监听分页变化
watch(() => [formInline.PageIndex, formInline.PageSize], () => {
  getPiciData()
}, { deep: true })
// 仓库选项
const wareHouseOptions = ref<Array<{warename: string, warehouseNo: string}>>([])

const GetSelectWareHouse = async () => {
  try {
    const response = await service.get("/api/app/standing__Book/select-ware-house")
    if (response.data.code === 200) {
      wareHouseOptions.value = response.data.resultData
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    ElMessage.error('获取仓库列表失败')
  }
}
// 单位选项
const Units = ref<Array<{unitscoding: string, unitName: string}>>([])

const GetSelectUnits = async () => {
  try {
    const response = await service.get("/api/app/goods/goods-unit-list")
    Units.value = response.data

  } catch (error) {
    console.error('获取单位列表失败:', error)
    ElMessage.error('获取单位列表失败')
  }
}
// 货品类型选项
const goodsTypes = ref<Array<{goodstypecoding: string, wGoodstypename: string}>>([])

const GetSelectTypes = async () => {
  try {
    const response = await service.get("/api/app/goods/goods-type-list")
    goodsTypes.value = response.data
  } catch (error) {
    console.error('获取货品类型列表失败:', error)
    ElMessage.error('获取货品类型列表失败')
  }
}
// 重置
const Reset = () => {
  formInline.Goodsname = ''
  formInline.Goodstypeid = ''
  formInline.GoodsUnitId = ''
  formInline.PiciCoding = ''
  formInline.Warename = ''
  formInline.ProductionTime = ''
  formInline.EndTime = ''
  formInline.PageIndex = 1
  getPiciData()
}

// 分页大小改变
const handleSizeChange = (val: number) => {
 formInline.PageSize  = val
  getPiciData()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  formInline.PageIndex = val
  getPiciData()
}

// 查看货品详情
const GetGoods = (row: any) => {
  console.log('查看货品详情:', row)
  // 这里可以跳转到货品详情页面
  ElMessage.info(`查看货品: ${row.goodsname}`)
}

// 查看批次详情
const viewDetails = (row: any) => {
  console.log('查看批次详情:', row)
  ElMessage.info(`查看批次: ${row.piciCoding}`)
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 导出数据
const exportData = () => {
  if (tableData.value.length === 0) {
    ElMessage.warning('没有数据可导出')
    return
  }
  
  // 这里可以实现导出功能，比如导出为Excel
  ElMessage.success('导出功能开发中...')
}

// 刷新数据
const refreshData = () => {
  getPiciData()
}


</script>

<style scoped>
.pici-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.data-container {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-section {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.table-section {
  margin-bottom: 20px;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.demo-form-inline .el-form-item {
  margin-right: 20px;
  margin-bottom: 10px;
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background-color: #fafafa;
  color: #333;
  font-weight: 600;
}

.el-table td {
  padding: 12px 0;
}

.el-button--link {
  padding: 0;
  height: auto;
}

.el-tag {
  border-radius: 4px;
}
</style>
